package com.test.springboot.alicloudoss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.*;
import com.test.springboot.alicloudoss.config.AliCloudOssConfig;
import com.test.springboot.alicloudoss.pojo.AlicloudOssPojo;
import com.test.springboot.alicloudoss.service.AlicloudOssService;
import com.test.springboot.alicloudoss.utils.AlicloudOssUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.List;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/8/10 18:43
 * @package com.test.springboot.alicloudoss.service.impl
 * @description 文件说明
 */

@Service
public class AlicloudOssServiceImpl implements AlicloudOssService {
    // 允许上传的格式
    private static final String[] FILE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    @Autowired
    private OSS ossClient;

    @Autowired
    private AliCloudOssConfig aliyunOssConfig;

    public AlicloudOssPojo upload(MultipartFile file,String filePath) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type : FILE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }

        //封装Result对象，并且将文件的byte数组放置到result对象中
        AlicloudOssPojo alicloudOssPojo = new AlicloudOssPojo();
        if (!isLegal) {
            alicloudOssPojo.setStatus("error");
            return alicloudOssPojo;
        }

        // 生成文件上传的完整路径
        String allFilePath = AlicloudOssUtil.getFilePath(file, filePath);

        // 上传到阿里云
        try {
            ossClient.putObject(aliyunOssConfig.getBucketName(), allFilePath, new
                    ByteArrayInputStream(file.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            alicloudOssPojo.setStatus("error");
            return alicloudOssPojo;
        }

        // 设置实体pojo 的参数
        alicloudOssPojo.setStatus("done");
        alicloudOssPojo.setResponse("success");
        //this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保存到数据库
        alicloudOssPojo.setName(this.aliyunOssConfig.getUrlPrefix() + allFilePath);
        alicloudOssPojo.setUid(String.valueOf(System.currentTimeMillis()));
        return alicloudOssPojo;
    }

    public List<OSSObjectSummary> list() {
        // 设置最大个数。
        final int maxKeys = 200;
        // 列举文件。
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunOssConfig.getBucketName()).withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    public AlicloudOssPojo delete(String fileName) {
        // 根据BucketName,objectName删除文件
        ossClient.deleteObject(aliyunOssConfig.getBucketName(), fileName);
        AlicloudOssPojo alicloudOssPojo = new AlicloudOssPojo();
        alicloudOssPojo.setName(fileName);
        alicloudOssPojo.setStatus("removed");
        alicloudOssPojo.setResponse("success");
        return alicloudOssPojo;
    }

    public void exportOssFile(OutputStream os, String fileName) throws IOException {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(aliyunOssConfig.getBucketName(), fileName);
        // 读取文件内容。
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int lenght = 0;
        while ((lenght = in.read(buffer)) != -1) {
            out.write(buffer, 0, lenght);
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
}
